<template>
  <list-card>
    <el-form ref="queryForm" slot="search" inline :model="queryParams" label-suffix="：" size="small">
      <el-form-item label="字典编码" prop="code">
        <el-input v-model="queryParams.code" clearable placeholder="请输入字典编码" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="字典名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入字典名称" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item class="search-btn">
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" type="info" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div slot="operator">
      <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleAdd">新增</el-button>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </div>

    <el-table v-if="refreshTable" slot="list" v-loading="loading" :data="dataList" :lazy="true" :load="treeLoad"
              :tree-props="{children: 'children', hasChildren: 'hasChild'}" class="list-table" row-key="id">
      <el-table-column label="字典名称" min-width="200px" prop="name" show-overflow-tooltip/>
      <el-table-column label="字典编码" min-width="120px" prop="code" show-overflow-tooltip/>
      <el-table-column label="排序" min-width="50px" prop="orderNum"/>
      <el-table-column label="说明" min-width="160px" prop="remark" show-overflow-tooltip/>
      <el-table-column class-name="small-padding fixed-width" fixed="right" label="操作" min-width="160px">
        <template v-slot:default="scope">
          <el-button icon="el-icon-plus" size="mini" type="text" @click="handleAdd(scope.row)">新增</el-button>
          <el-button icon="el-icon-edit" size="mini" type="text" @click="handleEdit(scope.row)">修改</el-button>
          <el-button icon="el-icon-delete" size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加或修改部门对话框 -->
    <el-dialog ref="dialog" :title="dialog.title" :visible.sync="dialog.open" :needMax="false" @confirm="handleSubmit"
              width="700px" @cancel="handleCancel">
      <el-form ref="form" :model="formdata" :rules="rules" label-suffix="：" label-width="120px">
        <el-row>
          <el-col v-if="formdata.pid !== 0" :span="24">
            <el-form-item label="上级字典" prop="pid">
              <a-tree-select v-model="formdata.pid" :getPopupContainer="selectParent"
                             :replaceFields="{key:'value', value: 'id'}"
                             :tree-data="tagOptions" allowClear style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字典名称" prop="name">
              <el-input v-model="formdata.name" placeholder="请输入字典名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字典编码" prop="code">
              <el-input v-model="formdata.code" placeholder="请输入字典编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="formdata.orderNum" :min="0" controls-position="right" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="字典说明" prop="remark">
              <el-input v-model="formdata.remark" controls-position="right" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button type="info" @click="handleCancel">取 消</el-button>
      </div> -->
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload ref="upload" :action="upload.url + baseUrl+ 'importData'" :auto-upload="false"
                 :disabled="upload.isUploading" :headers="upload.headers" :limit="1"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                 accept=".xlsx, .xls" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <!--          <div slot="tip" class="el-upload__tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport"/>-->
          <!--            是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button type="info" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </list-card>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {child, root, treeselect} from "@/api/tree";
import {checkExist, getOne,remove, save} from "@/api/base";
import {getToken} from "@/utils/auth";
import moment from "moment/moment";

export default {
  name: "Category",
  dicts: [],
  components: {},
  data() {
    return {
      baseUrl: '/system/category',
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 表格树数据
      dataList: [],
      // 部门树选项
      tagOptions: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      formdata: {},
      // 表单校验
      rules: {
        code: [
          {required: true, message: "字典编码不能为空", trigger: "blur"},
          {min: 2, max: 30, message: '长度在2到32个字符', trigger: 'blur'},
          {pattern: /^-?\w+$/, message: '只能包含数字、字母、下划线', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              checkExist('/system/category/', {'id': this.formdata.id, 'code': value}).then(response => {
                callback();
              }).catch(error => {
                callback(new Error(error.message))
              })
            }
          }
        ],
        // name: [
        //   {required: true, message: "字典名称不能为空", trigger: "blur"},
        //   {
        //     validator: (rule, value, callback) => {
        //       checkExist('/system/category/', {'id': this.formdata.id, 'name': value}).then(() => {
        //         callback();
        //       }).catch(error => {
        //         callback(new Error(error.message))
        //       })
        //     }
        //   }
        // ],
      },
      dialog: {
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
      },
      upload: {
        open: false,
        title: "",
        isUploading: false,
        updateSupport: 1,
        headers: {
          clientid: process.env.VUE_APP_CLINET,
          Authorization: "Bearer " + getToken()
        },
        url: process.env.VUE_APP_BASE_API + "/system/category/importData"
      },
      current: {}
    };
  },
  created() {
    this.resetQuery();
  },
  methods: {
    selectParent() {
      return this.$refs.dialog.$el
    },
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      if (this.baseUrl === undefined) {
        this.baseUrl = '/system/category/'
      }
      root(this.baseUrl, this.queryParams).then(response => {
        this.dataList = response.data;
        this.loading = false;
      });
    },
    // 树形动态加载表单数据：
    treeLoad(tree, treeNode, resolve) {
      child(this.baseUrl, tree.id, this.queryParams).then((res) => {
        return resolve(res.data);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      console.log(row)
      this.handleReset();
      if (row !== undefined) {
        this.formdata.pid = row.id;
        this.formdata.pcode = row.code;
      }
      treeselect(this.baseUrl).then(response => {
        this.tagOptions = response.data.datas;
        this.dialog.open = true;
        this.dialog.title = "新建字典";
      });
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.handleReset();
      getOne(this.baseUrl, row.id).then(response => {
        this.formdata = response.data;
        if (this.formdata.pid === '0') {
          this.formdata.pid = undefined;
        }
        this.dialog.open = true;
        this.dialog.title = "修改字典";
      });
      treeselect(this.baseUrl, {}).then(response => {
        this.tagOptions = response.data.datas;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"及其所有的子项的数据项？').then(() => {
        remove(this.baseUrl, row.id).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.toggleExpandAll();
        })
      })
    },
    /** 提交按钮 */
    handleSubmit: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          save(this.baseUrl, this.formdata).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.dialog.open = false;
            if (response.data.pid === '0') {
              this.getList()
            } else {
              this.toggleExpandAll();
            }
          });
        }
      });
    },
    // 取消按钮
    handleCancel() {
      this.dialog.open = false;
      this.handleReset();
    },
    // 表单重置
    handleReset() {
      this.resetForm("form");
    },
    handleExport() {
      this.download(this.baseUrl + '/exportData', {
        ...this.queryParams,
        ids: this.ids.join(','),
      }, `分类字典_${moment().format('YYYY-MM-DD')}.xlsx`, 'application/json;charset=utf-8')
    },
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(this.baseUrl + 'importTemplate', {}, `分类字典导入模板_${moment().format('YYYY-MM-DD')}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style lang="scss" scoped>
</style>
